package org.jsping.servlet;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.jsping.entity.Music;
import org.jsping.service.impl.MusicServiceImpl;
import org.jsping.util.TempData;

import com.alibaba.fastjson.JSON;

/**
 * 接收musicplay页面定时发送过来的请求,根据会话里面的mids来返回对应的数据
 * 请求list的话 则把会话中的mids发送过去
 * 请求删除的话,则删除请求过来的mid,再重新把设置会话中的list属性
 */
@WebServlet("/PlayServlet")
public class PlayServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

    public PlayServlet() {
        super();
    }

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		System.out.println("有请求进来了!");
		List<Integer> mids = (ArrayList<Integer>)request.getSession().getAttribute("mids");
		String content = "";
		/*拿到会话中存储的mids集合,用于做判断处理*/
		if(mids!=null) {
			/*只在数据更新的时候返回数据*/
			if(mids.size() != TempData.num) {
				TempData.num = mids.size();   //同时将num设置为集合大小的值
				//根据提供的集合去返回对应的数组集合
				/*可能这里返回的数据太多了,造成了连接中断?*/
				Map<String, Music> musics = new MusicServiceImpl().getMusics(mids);  
				content = JSON.toJSONString(musics);
				System.out.println("返回回去的内容:"+content);
				PrintWriter out = response.getWriter();
				out.print(content);
				out.flush();
				out.close();
			}
		}
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doGet(request, response);
	}
}
